<template>
	<div v-waterMarker class="merak-float" v-loading="loading">
		<div class="header">
			<div class="leftTitle">
				<!-- <div class="icon" @click="emit('close',state.refresh,props.typeId)">
					<el-icon size="20">
						<ArrowLeft />
					</el-icon>
				</div> -->
				<div class="title">{{$t('goods_document.add_document')}}</div>
			</div>
			<div class="btnBoxs">
				<el-button plain @click="emit('close',state.refresh,props.typeId)">{{$t('merak.cancel')}}</el-button>
				<el-button type="primary" plain
					@click="submitForm(ruleFormRef,true)">{{ $t("merak.save_continue") }}</el-button>
				<el-button type="primary" @click="submitForm(ruleFormRef,false)">{{ $t("merak.save") }}</el-button>
				<div class="icon" @click="emit('close',state.refresh,props.typeId)">
					<el-icon size="20">
						<Close />
					</el-icon>
				</div>
			</div>
		</div>
		<div class="content">
			<div class="merak-float-overflow-y">
				<el-form ref="ruleFormRef" labelPosition="top" :model="ruleForm" :rules="rules">
					<div class="group">
						<div class="titleHeader" @click="state.basicsMsg = !state.basicsMsg">
							<el-icon size="16" v-if="state.basicsMsg">
								<CaretRight />
							</el-icon>
							<el-icon size="16" v-else>
								<CaretBottom />
							</el-icon>
							<div class="group-title">{{$t("goods_attribute.basic_information")}}</div>
						</div>
						<el-row :gutter="40" v-if="!state.basicsMsg">
							<el-col :span="6">
								<el-form-item :label="$t('goods_document.goods_certify_no')" prop="goods_certify_no"
									:error="newRules.goods_certify_no">
									<el-input class="qf_input" type="text" v-model="ruleForm.goods_certify_no" maxlength="50"/>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item prop="start_date" :label="$t('goods_document.period_date')">
									<el-date-picker class="qf_date" type="daterange" v-model="validPeriod"
										:range-separator="$t('merak.rangto')" :format="format"
										:value-format="format" unlink-panels />
								</el-form-item>
							</el-col>

							<el-col :span="6">
								<el-form-item prop="goods_certify_type"
									:label="$t('goods_document.goods_certify_type')" :error="newRules.goods_certify_type">
									<el-select filterable class="qf_select"
										:placeholder="$t('merak.placeholder_select')"
										v-model="ruleForm.goods_certify_type">
										<el-option :label="item?.label" :value="item?.value"
											v-for="item in opstionsObjs?.documentList" :key="item?.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item prop="apply_name_factory"
									:label="$t('goods_document.apply_name_factory')" :error="newRules.apply_name_factory">
									<el-select filterable class="qf_select"
										:placeholder="$t('merak.placeholder_select')"
										v-model="ruleForm.apply_name_factory">
										<el-option :label="item?.label" :value="item?.value"
											v-for="item in opstionsObjs?.factoryList" :key="item?.value">
											<!-- <div v-html="item.label"></div> -->
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item prop="adult_child" :label="$t('goods_document.adult_child')" :error="newRules.adult_child">
									<el-radio-group v-model="ruleForm.adult_child">
										<el-radio v-for="option in opstionsObjs?.adultList" :value="option.value"
											:label="option.label" />
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item prop="type_id" :label="$t('goods_document.type_id')" :error="newRules.type_id">
									<el-select filterable class="qf_select"
										:placeholder="$t('merak.placeholder_select')" v-model="ruleForm.type_id">
										<el-option :label="item?.label" :value="item?.value"
											v-for="item in opstionsObjs?.typeList" :key="item?.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item prop="other_brands" :label="$t('goods_document.brand_title')"
									:error="newRules.other_brands" >
									<el-input class="qf_input" :placeholder="$t('goods_document.textarea_placeholder')"
										type="textarea" rows="4" v-model="ruleForm.other_brands" />
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item prop="hs_codes" :label="$t('goods_document.hs_codes')" :error="newRules.hs_codes">
									<el-input class="qf_input" :placeholder="$t('goods_document.textarea_placeholder')"
										type="textarea" rows="4" maxlength="500" v-model="ruleForm.hs_codes" />
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item prop="product_description"
									:label="$t('goods_document.product_description')" :error="newRules.product_description">
									<el-input class="qf_input" :placeholder="$t('goods_document.textarea_placeholder')"
										type="textarea" rows="4" v-model="ruleForm.product_description" />
								</el-form-item>
							</el-col>
						</el-row>
					</div>
					<div class="group" :class="state.propertyList?'':'group-table'">
						<div class="group-head">
							<div class="titleHeader" @click="state.propertyList = !state.propertyList">
								<el-icon size="16" v-if="state.propertyList">
									<CaretRight />
								</el-icon>
								<el-icon size="16" v-else>
									<CaretBottom />
								</el-icon>
								<div class="group-title">{{$t('goods_document.factory')}}</div>
							</div>
							<div class="btnBox">
								<el-button type="primary" plain
									@click="addRows">{{$t('goods_document.add_factory')}}</el-button>
							</div>
						</div>
						<div class="float-table-row" v-if="!state.propertyList">
							<div class="table-box">
								<basicTableSum ref="editTableRef" v-bind="tableConfig" @editFormFun="editFormClick">
									<template #factory_id="{ scope }">
										<el-select v-model="(scope as Record<string, any>).factory_id.value" filterable
											remote remote-show-suffix
											:placeholder="$t('goods_document.search_company_name')"
											:remote-method="(query: string) => handleRemote(query, scope.index)"
											@change="
									      value =>
									        ((scope as Record<string, any>).factory_id.label = opstionsObjs.companyList.find(option => option.value === value)?.label)
									    ">
											<el-option v-for="option in opstionsObjs.searchOptions"
												:value="option.value" :label="option.label" />
										</el-select>
									</template>
									<template #handle="{ row }">

										<el-button type="danger" link
											@click="delFun(row)">{{$t('merak.delete')}}</el-button>

									</template>
								</basicTableSum>
							</div>
						</div>
					</div>
					<div class="group" :class="state.fileList?'':'group-table'">
						<div class="group-head">
							<div class="titleHeader" @click="state.fileList = !state.fileList">
								<el-icon size="16" v-if="state.fileList">
									<CaretRight />
								</el-icon>
								<el-icon size="16" v-else>
									<CaretBottom />
								</el-icon>
								<div class="group-title">{{$t('goods_document.annex')}}</div>
							</div>
						</div>
						<div class="float-table-row" v-if="!state.fileList">
							<UploadFileMerak :path="Path.certify" v-model="state.fileArr" />
						</div>
					</div>
				</el-form>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
	import type { FormInstance, FormRules, } from "element-plus";
	import useDateFormat from "@/hooks/useDateFormat";
	import { nextTick, getCurrentInstance, ref, reactive, computed, watch, onMounted } from "vue";
	import basicTableSum from "@/components/MerakEditTable/components/basicTable/moreEdit.vue";
	import UploadFileMerak from "@/components/uploadFileMerak/index.vue";
	import { getDocumentInitData, postDocumentFormData, getCompanyOptions } from "@/api/modules/goodsArchive/document";
	import { failMsg, successMsg } from "@/utils/messageUtils";
	import { Path } from "@/api/modules/upload";

	const { format } = useDateFormat();
	const { proxy } = getCurrentInstance()!;
	const props = defineProps<{
		goodsId ?: string | number;

	}>();
	const ruleFormRef = ref<FormInstance>()
	const editTableRef = ref<FormInstance>()
	const loading = ref(true);
	const ruleForm = reactive<Record<string, any>>({
		goods_certify_no: "",//单证注册编号
		start_date: "",//开始时间
		end_date: "",//结束时间
		goods_certify_type: "",//单证类型
		apply_name_factory: "",//申请公司
		adult_child: 1,//年龄
		type_id: "",//商品类型
		other_brands: "",// 其他品牌
		hs_codes: "",//// 俄罗斯海关编码
		product_description: "",// 商品描述

	});
	//页面的select下拉数据
	const opstionsObjs = reactive({
		companyList: [],// 中国工厂/贸易公司
		documentList: [],//单证类型
		adultList: [],//年龄
		factoryList: [],//申请公司
		typeList: [],//商品类型
		searchOptions: [],//中国工厂/贸易公司过滤数据
	})
	const newRules = reactive<FormRules<RuleForm>>({})


	const rules = reactive<FormRules<RuleForm>>({
		goods_certify_no: [{ required: true, message: proxy!.$t("goods_document.goods_certify_no_valid") }],
		start_date: [{ required: true, message: proxy!.$t("goods_document.period_date_valid") }],
		other_brands: [{ required: true, message: proxy!.$t("goods_document.other_brands_valid") }],
		apply_name_factory: [{ required: true, message: proxy!.$t("goods_document.apply_name_factory_valid") }],
		hs_codes: [{ required: true, message: proxy!.$t("goods_document.hs_codes_valid") }],
	})

	const validPeriod = computed({
		get: () => {
			const { start_date, end_date } = ruleForm;
			if (!!start_date && !!end_date) {
				return [start_date, end_date] as [string, string];
			}
			return;
		},
		set: value => {
			const [start_date, end_date] = value ?? [];
			ruleForm.start_date = start_date;
			ruleForm.end_date = end_date;
		}
	});
	const emit = defineEmits<{
		close : [refresh: boolean];
	}>();

	const state = reactive<{
		copy : Record<string, any>;
		documentType : OptionType[];
		goodType : OptionType[];
		applyType : OptionType[];
		applySearchResult : OptionType[];
		ageType : OptionType[];
		fileArr : OptionType[];
		title : string;
		basicsMsg : boolean;
		propertyList : boolean;
		fileList : boolean;
	}>({
		copy: {},
		documentType: [],
		goodType: [],
		applyType: [],
		applySearchResult: [],
		ageType: [],
		fileArr: [],
		title: "",
		basicsMsg: false,
		propertyList: false,
		fileList: false,
	});

	const addRows = () => {
		editStatusType.value = "add";
		let obj = {
			factory_id: {
				label: "",
				value: "",
			}
		};
		tableData.value.push(obj);
		nextTick(() => {
			editTableRef.value.initBottomScroll()
		})
	}
	type EditTableDataType = Record<
		string,
		{
			value ?: string | number;
			label ?: string;
			errTip ?: string;
		}
	>;
	const tableData = ref([]);
	const headConfig = reactive({});//头部配置是否可编辑 
	const editStatusType = ref("");
	const tableConfig = reactive<{
		headData : Array<Record<string, any>>;
		tableData : EditTableDataType[];
		headConfig : Record<string, any>;
	}>({
		headData: [
			{
				field: "factory_id",
				title: proxy!.$t("goods_document.factory_name_certify")
			},
		],
		tableData: tableData,
		headConfig: {
			factory_id: { isEdit: true }
		}
	})
	//获取初始化数据
	const initMsg = () => {
		let data = {};
		console.log(props.goodsId)
		if (props.goodsId != "") {
			data.goods_certify_id = props.goodsId
		}
		getDocumentInitData(data).then(({ code, data }) => {
			if (code == 2000) {
				opstionsObjs.adultList = data.dataarr.adult_child;//年龄
				opstionsObjs.documentList = data.dataarr.goods_certify_type;//单证类型
				opstionsObjs.factoryList = data.dataarr.factory_trade;//申请公司
				opstionsObjs.typeList = data.dataarr.type_id;//商品类型
				if (props.goodsId != "" && props.goodsId != undefined) {

					ruleForm.goods_certify_no = data.defaults.goods_certify_no;
					ruleForm.start_date = data.defaults.start_date;
					ruleForm.end_date = data.defaults.end_date;
					ruleForm.goods_certify_type = data.defaults.goods_certify_type;
					ruleForm.apply_name_factory = data.defaults.apply_name_factory;
					ruleForm.adult_child = data.defaults.adult_child;
					if(data.defaults.type_id){
						if(data.defaults.type_id == 0){
							ruleForm.type_id = ""
						} else {
							ruleForm.type_id = data.defaults.type_id;
						}
					} else {
						ruleForm.type_id = "";
					}

					ruleForm.other_brands = data.defaults.other_brands;
					ruleForm.hs_codes = data.defaults.hs_codes;
					ruleForm.product_description = data.defaults.product_description;
					state.fileArr = data.defaults.filesList;
					let newArr = [];

					if (data.defaults.companyList) {
						data.defaults.companyList.map(tableItem => {
							newArr.push({
								factory_id: {
									label: tableItem.factory_name_certify,
									value: tableItem.factory_id,
								},
							})
						})
						tableConfig.tableData = newArr;
					}
					setTimeout(() => {
						loading.value = false;
					}, 0)
				} else {
					loading.value = false
				}
			}
		})
	}
	const isShowTable = ref(false);
	const showTable = (e) => {
		if (ruleForm.cc_prop_type == 'dropdown') {
			isShowTable.value = true;
		} else {
			isShowTable.value = false;
		}

	}
	const delFun = (e) => {
		tableConfig.tableData.splice(e.index, 1);
	}
	const editFormClick = (e) => {
		const idx = e.index;
		const editItem = {};
		Object.assign(editItem, e);
		delete editItem["index"];
		tableConfig.tableData[idx] = editItem;
	}


	const submitForm = async (formEl : FormInstance | undefined, isHide : boolean) => {

		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				let tableDataArr = [];
				tableDataArr = editTableRef.value.submitData();
				let postData = ruleForm
				if (tableDataArr && tableDataArr.length > 0) {
					let fArr = []
					tableDataArr.map(item=>{
						fArr.push(item.factory_id)
					})
					postData.factory = fArr;
				}
				
				if (state.fileArr.length >0){
					let fileData = [];
					state.fileArr.map(item=>{
						if(item.status){
							if(item.status == 'success'){
								if(item.response){
									fileData.push(item.response)
								}
							}
							
						} else {
							fileData.push(item)
						}
					})
					postData.files = fileData;
				}
				if (Object.keys(newRules).length > 0) {
					Object.keys(newRules).map((key) => {
						newRules[key] = undefined;
					});
				}
				postData.other_brands = postData.other_brands.replace(/\n/g, '')
				postData.hs_codes = postData.hs_codes.replace(/\n/g, '')
				postDocumentFormData(postData).then(({ code, data, message,errors }) => {
					if (code == 2000) {
						successMsg(proxy!.$t("goods_attribute.add_success"));
						formEl.resetFields()
						tableConfig.tableData = [];
						state.refresh = true;
						if (!isHide) {
							emit('close', state.refresh)
						}
					} else {
						if(Object.keys(errors).length !== 0){
							Object.assign(newRules,errors);
						} else {
							failMsg(message)
						}
					}
				})
			} else {
				console.log('error submit!', fields)
			}
		})
	}
	const handleRemote = (query : string, index : number) => {
		const options = !!query ? opstionsObjs.companyList.filter(option => option.label.toLowerCase().includes(query.toLowerCase())) : [];
		const excludeIds = tableConfig.tableData.map((item, idx) => (index === idx ? undefined : item.factory_id?.value)).filter(Boolean);
		opstionsObjs.searchOptions = options.filter(option => !excludeIds.includes(option.value));
	};
	//获取中国工厂/贸易公司
	const getCompanyList = () => {
		getCompanyOptions().then(({ code, data, message }) => {
			if (code == 2000) {
				opstionsObjs.companyList = data;
				// console.log(data)
				// let headCon = {
				// 	factory_id: {
				// 		type: "select",
				// 		options: data
				// 	},
				// }
				// console.log(headCon)
				// Object.assign(headConfig, headCon);
			} else {

			}
		})
	}
	onMounted(async () => {
		await getCompanyList()
		await initMsg();
		let tableDataArr = [];
		tableData.value = tableDataArr;
	})
</script>

<style type="text/css">
	@import "./addCard.scss";
</style>